// src/models/User.ts
import {
  DataTypes,
  Model,
  Optional,
  Association,
  BelongsToManyAddAssociationMixin,
  BelongsToManyGetAssociationsMixin,
  BelongsToManySetAssociationsMixin,
} from "sequelize";
import sequelize from "../config/db";
import Tags from "./Tags";
import ArticleTag from "./ArticleTag";

// 定义用户模型接口
interface ArticlesAttributes {
  id: number;
  title: string;
  content: string;
  author_id: string;
  category_id: string;
  views: number;
  status: number;
  tags: string;
  cover_image: string;
}

interface UserCreationAttributes extends Optional<ArticlesAttributes, "id"> {}

class Articles
  extends Model<ArticlesAttributes, UserCreationAttributes>
  implements ArticlesAttributes
{
  public id!: number;
  public title!: string;
  public content!: string;
  public author_id!: string;
  public category_id!: string;
  public views!: number;
  public status!: number;
  public tags!: string;
  public cover_image!: string;

  // 多对多自动生成的方法
  public addTag!: BelongsToManyAddAssociationMixin<Tags, Tags[]>;
  public getTags!: BelongsToManyGetAssociationsMixin<Tags>;
  public setTags!: BelongsToManySetAssociationsMixin<Tags, number>;
  // 关联关系
  public static associations: {
    tags: Association<Articles, Tags>;
  };
}

/**
 *
 * @
 *
 */
Articles.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    title: {
      type: DataTypes.STRING(50),
      allowNull: false,
      validate: {
        notEmpty: true, // 不允许为空字符串
      },
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: false,
    },
    author_id: {
      type: DataTypes.STRING(50),
      allowNull: false,
    },
    cover_image: {
      type: DataTypes.STRING(50),
      allowNull: false,
    },
    category_id: {
      type: DataTypes.STRING(50),
      allowNull: true,
    },
    views: {
      type: DataTypes.TINYINT(),
      allowNull: true,
    },
    status: {
      type: DataTypes.TINYINT(),
      defaultValue: 1, // 默认启用
    },
    tags: {
      type: DataTypes.JSON, // 定义为 JSON 类型
      allowNull: true,
      defaultValue: [], // 默认值为空数组
    },
  },
  {
    tableName: "articles",
    sequelize, // sequelize 实例
    timestamps: true,
  }
);

export default Articles;
